package org.eclipseuseradmin.internal.ui.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.EvaluationContext;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipseuseradmin.ui.BaseRoleElementAdapter;
import org.eclipseuseradmin.ui.IRoleElement;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;

public class RemoveHandler extends AbstractHandler {

	public Object execute(ExecutionEvent event) throws ExecutionException {

		Role selectedElement = null;
		Group parentOfselectedElement = null;
		ISelection selection = HandlerUtil.getCurrentSelection(event);

		if (selection instanceof TreeSelection) {
			selectedElement = (Role) ((TreeSelection) selection)
					.getFirstElement();
			TreePath[] paths = ((ITreeSelection) selection)
					.getPathsFor(selectedElement);
			if (paths[0].getSegmentCount() > 1) {
				parentOfselectedElement = (Group) paths[0].getSegment(paths[0]
						.getSegmentCount() - 2);
			}
		}

		if (parentOfselectedElement instanceof Group) {

			IRoleElement adapter = BaseRoleElementAdapter
					.adapt(parentOfselectedElement);
			adapter.removeChild(selectedElement);
			adapter = BaseRoleElementAdapter.adapt(selectedElement);
			adapter.removeParent(parentOfselectedElement);
		}

		return null;
	}

	@Override
	public void setEnabled(Object evaluationContext) {

		EvaluationContext context = (EvaluationContext) evaluationContext;
		StructuredSelection selection = (StructuredSelection) context
				.getVariable("selection");
		if (selection == null || selection.isEmpty()
				|| !(selection instanceof TreeSelection)) {
			setBaseEnabled(false);
			return;
		}

		// find parent element of the selection
		Object selectedElement = ((TreeSelection) selection).getFirstElement();
		TreePath[] paths = ((ITreeSelection) selection)
				.getPathsFor(selectedElement);
		Object parentOfselectedElement = null;
		if (paths.length > 0 && paths[0].getSegmentCount() > 1) {
			parentOfselectedElement = paths[0].getSegment(paths[0]
					.getSegmentCount() - 2);
		}

		if (selectedElement instanceof Role
				&& parentOfselectedElement instanceof Group) {
			setBaseEnabled(true);
			return;
		}

		setBaseEnabled(false);
	}

}
